package com.cat.greedyAlgorithm;

import java.util.Arrays;
import java.util.Map;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/equal-sum-arrays-with-minimum-number-of-operations/
 * @create 2025/8/24 16:42
 * @since JDK17
 */

public class Solution24 {
    public int minOperations(int[] nums1, int[] nums2) {
        int n = nums1.length, m = nums2.length, ans = 0;
        if (n > m * 6 || m > n * 6) {
            return -1;
        }
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int sum1 = Arrays.stream(nums1).sum();
        int sum2 = Arrays.stream(nums2).sum();
        if (sum1 < sum2) {  // 始终让sum1保持最大
            int t = sum1;
            sum1 = sum2;
            sum2 = t;
            int[] temp = nums1;
            nums1 = nums2;
            nums2 = temp;
            n = nums1.length;
            m = nums2.length;
        }

        for (int i = n - 1, j = 0; i >= 0 || j < m; ) {
            if (j < m && nums1[i] - 1 < 6 - nums2[j]) {
                sum2 = Math.min(sum2 + 6 - nums2[j++], sum1);
            } else {
                sum1 = Math.max(sum1 - nums1[i--] + 1, sum2);
            }
            ans++;
            if (sum1 == sum2) {
                return ans;
            }
        }

        return ans;
    }
}
